// import ListViewPage from '@page/list-view-page';
import {observable, action,} from 'mobx';
import {Tools, Bubble, Modal} from 'weaver-mobile';
import { Form ,Comment, SelectPage,Reply , ListPage, CKRichText, AtSomeone } from 'weaver-mobile-page';
import * as API_LIST from '../../api/create';
import { Base64 } from 'js-base64';
const jq = require('../../util/jquery') ;
const alert = Modal.alert;
const getLabel = Tools.getLabel;

export default class ViewWorkplanStore {
    @observable selectPage = new SelectPage.Store({route: '/detail'})
    @observable test = 1;
    @observable workplanid = '';//1508 1495
    @observable isfromchatshare = '';
    @observable isCreater = false;//是否为日程创建人
    @observable isfromMessageCenter = '';
    @observable sharer = '';
    @observable isDiscuss = '';
    @observable fromtype = '';
    @observable pageSize = 10;
    @observable pageNum = 0;
    @observable form = new Form.Store({route: '/detail'});
    @observable editConditions = {};
    @observable workplanName = ''
    @observable userName = ''
    @observable pageSize = 10;
    @observable pageNum = 0;
    @observable replyVisible = false;
    @observable beginDate = '';
    @observable beginTime = '';
    @observable endDate = '';
    @observable endTime = '';
    @observable comment = new Comment.Store({
      getComment: this.getComment,
      operate: this.operateExchange,
    });
    @observable attachList = [];
    @observable reply = new Reply.Store({getAttachList: this.initReplyAttachList,getAtConfig: this.getAtConfig});
    @observable exchangeListStore = new ListPage.Store();
    @observable btnGroup = [];
    @observable meetingLink = '';
    @observable noRight = false;
    @observable noData = false;
    @observable noSecretRight = false;
    //临时解决打开文档，流程问题
    @observable overWriteOpenDoc = false;
    @observable openDocFunc = window.openLink&&window.openLink.openDocument;
    @observable overWriteOpenWF = false;
    @observable openWFFunc = window.openLink&&window.openLink.openWorkflow;
    @observable optionId = '';
    @observable writeReply = null;
    @observable exchangeText = '';
    @observable fromType = '';
    @observable otherModuleCloseWP = false;

    @observable isSingelViewWorkplan = false; // 判断是否为单页进入
    @observable isSingleHasWorkplanId = false; // 单页进入有workplanid
    @observable replySubmitLoading = false;
    @observable atUserStore = new AtSomeone.Store();
    @observable atList = [];
    

    changeWorkplanID = (workid) => {
      this.workplanid = workid;
    }

    initWorkPlan = ()=>{
      this.noRight = false;
      this.noData = false;
      this.noSecretRight = false;
      this.otherModuleCloseWP = false;
    }
    setParams = (params = {}, callback) => {
      Object.keys(params).forEach(key => {
        this[key] = params[key];
      });
      typeof(callback) === 'function' && callback();
    }

    getPreview = (params, callback, callback2) => {
      let param = {...params,workid: this.workplanid,beginDate: this.beginDate,beginTime: this.beginTime,endDate: this.endDate,endTime: this.endTime,};
      let pathstr = window.location.hash && window.location.hash.split('#');
      this.from = new Form.Store({route: `${pathstr[1]}`});
      this.overWriteOpenWF = false;
      this.overWriteOpenDoc = false;
      if(this.fromType != 'crm'){
        window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(384902,'查看日程') })
      }
      API_LIST.viewWorkplanBaseData(param).then((result) => {
        this.btnGroup = [];
        this.form.initForm(result.data, `${pathstr[1]}`);
        if(this.form && this.form.formParams && this.form.formParams.planName) {// 过滤br
          let br = new RegExp(/&lt;br&gt;/g);
          let name = this.form.formParams.planName.replace(br, ' ');
          this.form.updateField('planName', name);
        }
        result.error && result.error === 'noright' && this.setParams({noRight: true,noData:false,noSecretRight:false})
        result.error && result.error === 'noData' && this.setParams({noRight: false,noData:true,noSecretRight:false})
        result.error && result.error === 'noSecretRight' && this.setParams({noRight: false,noData:false,noSecretRight:true})
        result.btn && result.btn.map(item => {
          if(item.method === 'doShare' || item.method === 'doLog') {

          }else{
            this.btnGroup.push(item)
          }
          return '';
        })
        result.data && result.data[0] && result.data[0].items && result.data[0].items.map(res => {
          if(res.domkey[0] === 'meetingIDs') {
            let meetid = res.browserConditionParam.replaceDatas[0].id;
            this.meetingLink = `spa/workplan/static4mobile/index.html#/calendar/detail?meetingId=${meetid}`
          }
          return '';
        })
        this.isCreater = result.isCreater;
        this.fromtype = result.fromModule || ''
        result.data && result.data[1] && result.data[1].items && result.data[1].items.map(res => {
          if(res.domkey[0] === 'docIDs') {
            if(window.openLink && window.openLink.openDocument && !this.overWriteOpenDoc){
              let workid = this.workplanid
              window.openLink.openDocument = function () {
                return function (docId, params2, type) {
                  var search = "";
                  var url = "/spa/document/static4mobile/index.html#/doc/" + docId + '?workplanid='+workid;
                  window.openLink(url, type)
                }
              }();
              this.overWriteOpenDoc = true;
            }
          }
          if(res.domkey[0] === 'requestIDs') {
            if(window.openLink && window.openLink.openWorkflow && !this.overWriteOpenWF){
              let workid = this.workplanid
              window.openLink.openWorkflow = function () {
                return function (url, callbackFun, returnUrl) {
                  if (window.em && typeof window.em.checkJsApi === "function" && window.em.checkJsApi("openLink") && window.em.checkJsApi("closeWindow") && window.navigator.userAgent.indexOf("E-Mobile") > -1) {
                    var title = "表单详情";
                    if (window.e9_locale && window.e9_locale.label) {
                      title = window.e9_locale.label[500244] || "表单详情";
                    }
                    url = url + '&fromModul=workplan&modulResourceId='+workid
                    window.em.openLink({
                      openType: 2,
                      title: title,
                      url: url
                    });
                    if (typeof callbackFun === "function") {
                      window.em.ready(function(){
                        window.em.registerBroadcast({
                          name: "_closeWfFormCallBack",
                          action: function (argument) {
                            if (typeof argument === "string") {
                              argument = JSON.parse(argument);
                            }
                            callbackFun(argument.text);
                          }
                        });
                      });
                    }
                  } else {
                    //window.open(url);   //微信、钉钉客户端open就等于location.href
                    window.location.href = url+'&fromModul=workplan&modulResourceId='+workid;
                    if (returnUrl === "") {
                      returnUrl = window.location.href;
                      if (returnUrl.indexOf("/spa") > -1) {
                        returnUrl = returnUrl.substr(returnUrl.indexOf("/spa"));
                      }
                    }
                    sessionStorage.setItem("__wf__openform__returnurl__", returnUrl);
                    if (typeof callbackFun === "function") {
                      window.__closeFormCallBack = callbackFun;
                    }
                  }
                }
              }();
              this.overWriteOpenWF = true;
            }
          }
          return '';
        })
      })
    }

    getComment = (param) => {
      this.pageNum = this.pageNum + 1;
      this.noRight = false;
      this.noData = false;
      this.noSecretRight = false;
      return Tools.callApi({
        url: '/api/workplan/exchange/getExchangeList',
        method: 'POST',
        params: {
          ...param,
          workplanid: this.workplanid,
          ismobile: '1',
          isfromchatshare:this.isfromchatshare,
          sharer:this.sharer,
          pageNum:this.pageNum,
          pageSize:this.pageSize
        },
      }).then(action((res) => {
        if(Array.isArray(res.replyList)) {// 过滤内容中的a标签
          res.replyList = res.replyList.map(v => {
            let contentStr = `${Base64.decode(v.content)}`;
            contentStr = contentStr.replace(/<\/?a(.*?)>/g, '');
            v.content = Base64.encode(contentStr);
            return v;
          });
        }

        res.error && res.error === 'noright' && this.setParams({noRight: true,noData:false,noSecretRight:false})
        res.error && res.error === 'noData' && this.setParams({noRight: false,noData:true,noSecretRight:false})
        res.error && res.error === 'noSecretRight' && this.setParams({noRight: false,noData:false,noSecretRight:true})
        if(!res.error){
          this.workplanName = res.workplanName;
          this.userName = res.username
          return res;
        }
        
      }));
    }

    operateExchange = (params) => {
      const {type, data, parent} = params;
      if (data) {
        this.userid = data.userid;
        this.workdate = data.workdate;
        this.optionId = data.replyId.indexOf('==') !== -1 ? '' : data.replyId;
      }
      if (type.type === 'delete') {
        alert(getLabel(15172, '系统提示'),getLabel(15097,"确定要删除吗？"),[
          { text: getLabel(386789, '取消') },
          {
            text: getLabel(386788, '确认'),
            onPress: () => {
              let deleteParams = {
                id: data.replyId,
              }
              return API_LIST.deleteExchange(deleteParams).then(res => {
                if(res.status){
                  this.pageNum = 0;
                  this.comment.getDatas();
                  this.reply.doClear();
                  Bubble.success('操作成功!', 1);
                }else{
                  alert(res.error ? res.error : `${getLabel(384137,'操作失败！')}`);
                }
              })
            }
          },
        ])
      }else if (type.type === 'bianji') {

      }
    }

    setExchangeText = (val) => {
      this.exchangeText = val;
    }

    getAtConfig = () => (
      new Promise((resolve) => {
        resolve({
          atConfig: {
            key: 'at',
            path: '/calendar/detail/discussData',
            config: {
              type: 1,
              isSingle: true,
            },
          },
        });
      })
    )

    getExchangeHrmList= (params,pathname)=>{
      return API_LIST.getExchangeHrmList(params).then((result) => {
        this.exchangeListStore = new ListPage.Store({route:`${pathname}/exchangeHrmList`});
        this.atList = result.atList;
        this.exchangeListStore.setState({data:result.atList});
        this.atUserStore = new AtSomeone.Store({route:`${pathname}/remarkat`});
      })
    }

    groupToggle = (...arg) => {
      let title = arg[0];
      let status = arg[1];
      this.form.conditioninfo = this.form.conditioninfo.map(res => ({
        ...res,
        ...(res.title === title ? {show: status} : {})
      }));
    }


  // 删除日程
  getDeleteWorkplan = (params, callback) => {
    API_LIST.deleteWorkplan(params).then(res => {
      typeof(callback) === 'function' && callback(-1);
      return res.status;
    });
  }

  // 完成日程
  getFinishWorkplan = (params,callback) => {
    API_LIST.finishWorkplan(params).then(res => {
      typeof(callback) === 'function' && callback(-1);
    });
  }

  // 删除周期日程
  deleteModuleWorkplan = (params,callback) => {
    API_LIST.deleteModulWorkplan(params).then(res => {
      typeof(callback) === 'function' && callback(-1);
    });
  }

  setReplyConfig = () => {
    this.writeReply = new CKRichText.Store({reply:{ getAttachList: this.initReplyAttachList, getAtConfig: this.getAtConfig}});
  }

  initReplyAttachList = () => {
    const fullUrl = window.location.hash.split('#')[1];;
    const onlyUrl = fullUrl.split('?')[0]
    this.pageNum = this.pageNum + 1;
      return Tools.callApi({
        url: '/api/workplan/exchange/getExchangeAttach',
        method: 'POST',
        params: {
          workplanid: this.workplanid,
          ismobile: '1'
        },
      }).then(
        action((res) => {
        let attachList=[]
        if(res.relatedwf){
          attachList.push({
            key: 'workflow', // 字符串
            type: 'browser',
            path: `${onlyUrl}/browser`,
            config: {
              type: 16,
              isSingle: false,
              hasAdvanceSerach: true,
              dataParams:{
                secretLevel: res.secretLevel
              }
            },
            iconType: 'flow',
            iconBgColor: '#61A8F5',
            text: getLabel(30045, '流程'),
          })
        }
        if(res.docids){
          attachList.push({
            key: 'doc', // 字符串
            type: 'browser',
            path: `${onlyUrl}/browser`,
            config: {
              type: 37,
              isSingle: false,
              hasAdvanceSerach: true,
              dataParams:{
                secretLevel: res.secretLevel
              }
            },
            iconType: 'file',
            iconBgColor: '#F3B04C',
            text: getLabel(22243, '文档'),
          })
        }
        if(res.relatedcus){
          attachList.push({
            key: 'customer', // 字符串
            type: 'browser',
            path: `${onlyUrl}/browser`,
            config: {
              type: 18,
              isSingle: false,
              hasAdvanceSerach: true,
              dataParams:{
                secretLevel: res.secretLevel
              }
            },
            iconType: 'blog-personal',
            iconBgColor: '#B32E37',
            text: getLabel(136, '客户'),
          })
        }
        if(res.relatedprj){
          attachList.push({
            key: 'project', // 字符串
            type: 'browser',
            path: `${onlyUrl}/browser`,
            config: {
              type: 135,
              isSingle: false,
              hasAdvanceSerach: true,
              dataParams:{
                secretLevel: res.secretLevel
              }
            },
            iconType: 'task-list',
            iconBgColor: '#F3B04C',
            text: getLabel(101, '项目'),
          })
        }
        if(res.relateddoc){
          attachList.push({
            key: 'upload', // 字符串
            type: 'upload',
            path:`${onlyUrl}`,
            config: {
              ...res.relateddoc
            },
            iconType: 'file',
            iconBgColor: '#F3B04C',
            text: getLabel(156, '附件'),
          })
        }
        // this.replyVisible = true;
        return {attachList: attachList}
      }))
    }

    @action('回复组件的显隐')
    setReplyVisible = (x) => {
      this.replyVisible = x;
    }
  
    submitReply = (datas) => {
      let cusValue = '';
      let docValue = '';
      let wfValue = '';
      let proValue = '';
      let uploadValue = '';
      datas.attach&&datas.attach.customer&&datas.attach.customer.forEach((element, index) => {
        cusValue += cusValue===''?element.id:','+element.id
      });
      datas.attach&&datas.attach.doc&&datas.attach.doc.forEach((element, index) => {
        docValue += docValue===''?element.id:','+element.id
      });
      datas.attach&&datas.attach.workflow&&datas.attach.workflow.forEach((element, index) => {
        wfValue += wfValue===''?element.id:','+element.id
      });
      datas.attach&&datas.attach.project&&datas.attach.project.forEach((element, index) => {
        proValue += proValue===''?element.id:','+element.id
      })
      datas.attach&&datas.attach.upload&&datas.attach.upload.forEach((element, index) => {
        uploadValue += uploadValue===''?element.id:','+element.id
      })
      let params = {
        remark: datas.text,
        workplanid: this.workplanid,
        //相关客户
        relatedcus :cusValue,
        //相关文档
        docids :docValue,
        //相关流程
        relatedwf :wfValue,
        //相关附件
        relateddoc :uploadValue,
        //相关项目
        projectIDs :proValue,
        isfromchatshare:this.isfromchatshare,
        sharer:this.sharer,
      }
      this.replySubmitLoading = true;
      API_LIST.submitReply(params).then((result) => {
        this.replySubmitLoading = false;
        if(result.status === true){
          this.pageNum = 0;
          this.comment.getDatas();
          this.reply.doClear();
          Bubble.success('操作成功!', 1);
        }
      })
      //发送消息通知
      const uidArray = [];
      jq(datas.text).find("a[atsome]")
      .each(function(item) {
        uidArray.push(jq(this).attr("atsome-uid"));
      });
      API_LIST.pushMessage({
        title: this.workplanName,
        context: `${this.userName}：<p>${datas.text}`,
        groupCode: "2211",
        linkurl: `/spa/workplan/static/index.html#/main/wp/workPlanCreateSingle?workPlanId=${this.workplanid}&activeKey=7`,
        linkMobileUrl: `/spa/workplan/static4mobile/index.html#/detail/discussData?workplanId=${this.workplanid}&isDiscuss=1`,
        userid: uidArray.join(",")
      })
      // const atLists = this.reply.getAtList();
      // if(atLists.length > 0){
      //   let uids = [];
      //   atLists.forEach((data,index)=>{
      //     uids.push(data.id)
      //   })
      //   API_LIST.pushMessage({
      //     title: this.workplanName,
      //     context: `${this.userName}：<p>${datas.text}`,
      //     groupCode: "2211",
      //     linkurl: `/spa/workplan/static/index.html#/main/wp/workPlanCreateSingle?workPlanId=${this.workplanid}&activeKey=7`,
      //     linkMobileUrl: `/spa/workplan/static4mobile/index.html#/detail/discussData?workplanId=${this.workplanid}&isDiscuss=1`,
      //     userid: uids.join(",")
      //   })
      // }
    }

    setPageNum = (val) => {
      this.pageNum = val;
    }
}